import React, { Component } from 'react'
import {
  View, ListView, Image, Text, StyleSheet, ImageBackground,
  TouchableOpacity, DeviceEventEmitter
} from 'react-native'
import CardView from 'react-native-cardview'
import navigationhelper from "src/components/navigationhelper"
import { pageWidth } from 'src/constants'
import Divider from 'src/components/Divider'
import RefreshLoadListView from 'src/components/RefreshLoadListView'
import { inject, observer } from "mobx-react/native"
import Layer from "src/components/Layer"

let ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 })


@inject('userAuth', 'cardManager')
@observer
export default class CardTabList extends Component {

  constructor(props) {
    super(props)
    this.mounted = false
    this.isRefresh = true
    this.pageNo = 0
    this.state = {
      isLoading: !props.dataList || !props.dataList.length
    }
  }


  componentDidMount() {
    this.deEmitter = DeviceEventEmitter.addListener('refreshCardManager', () => {
      this.handleRefreshDatas()
    });

    this.mounted = true
    this.handleRefreshDatas()
  }

  componentWillUnmount() {
    this.mounted = false
    this.deEmitter.remove()
  }

  refListView = (ref) => {
    this.listView = ref
  }

  handleRefreshDatas = () => {
    this.handleSendRequest()
  }

  handleLoadMoreDatas = () => {
    this.handleSendRequest()
  }

  handleSendRequest = () => {
    this.setState({ isLoading: true })
    this.props.cardManager.fetchCardList({
      token: this.props.userAuth.token,
      type: '02',
      status: this.props.status
    }).then((res) => {
      this.setState({ isLoading: false })
    }).catch(() => {
      this.setState({ isLoading: false })
    })
  }

  renderAddNewCard = () => {
    let { dataList } = this.props
    let length = dataList && dataList.length || 0
    return (
      <CardView
        style={[styles.cardStyle, {
          marginTop: length > 0 ? 14 : 18
        }]}
        cardElevation={2}
        cardMaxElevation={2}
        cornerRadius={8}>
        <TouchableOpacity style={[styles.hContainer, {
          width: pageWidth - 32, height: (pageWidth - 32) / 343 * 155
        }]}
          onPress={() => {
            if (this.props.userAuth.currentUser.real_name_status === 1) {
              navigationhelper.navigate('AddCardView')
            } else {
              Layer.showMsg('请实名认证后再来')
            }
          }}>
          <View style={styles.addCardContent}>
            <Text style={{ fontSize: 12, color: '#8e8e93' }}>
              {'帮助'}
            </Text>
            <View style={{ height: 10 }} />
            <Text style={{
              fontSize: 16, color: '#2e2e2e', fontWeight: 'bold', lineHeight: 20
            }}>
              {'添加一张信用卡\n以制定你的还款计划'}
            </Text>
            <View style={{ flex: 1 }} />
            <Text style={{ fontSize: 16, color: '#ff2121', fontWeight: 'bold' }}>
              {'现在就去'}
            </Text>
          </View>
          <View style={{ flex: 1 }} />
          <Image
            style={{
              width: (pageWidth - 32) / 343 * 155 / 310 * 288 * 2,
              height: (pageWidth - 32) / 343 * 155 * 2,
              resizeMode: 'cover'
            }}
            source={require('src/assets/icon_add_new_card.png')} />
        </TouchableOpacity>
      </CardView>
    )
  }

  renderRow = (rowData, sectionId, rowID) => {
    if (!rowData) return null
    if (!this.props.status && rowData.type === 'addCard') {
      return this.renderAddNewCard()
    }
    let statusText = <Text style={styles.status}>未制定</Text>;
    if (rowData.plan_status === 1) {
      statusText = <Text style={styles.statusMaked}>已制定</Text>
    } else if (rowData.plan_status === 2) {
      statusText = <Text style={styles.statusJinxinzhong}>进行中</Text>
    } else if (rowData.plan_status === 3) {
      statusText = <Text style={styles.statusComplate}>已完成</Text>
    } else if (rowData.plan_status === 4) {
      statusText = <Text style={styles.statusCancel}>已取消</Text>
    } else if (rowData.plan_status === 5) {
      statusText = <Text style={styles.statusFailed}>已失败</Text>
    }

    return (
      <TouchableOpacity activeOpacity={0.8} onPress={() => {
        if (rowData.plan_status === 0 || rowData.plan_status === 3 || rowData.plan_status === 4 || rowData.plan_status === 5) {
          navigationhelper.navigate('MakePlanView', { cardId: rowData.id })
        } else {
          Layer.showMsg('已制定计划')
        }
      }}>
        <CardView
          style={[styles.cardStyle, {
            marginTop: parseInt(rowID) > 0 ? 14 : 18
          }]}
          cardElevation={2}
          cardMaxElevation={2}
          cornerRadius={8}>
          <View style={styles.itemContainer}>
            <View style={[styles.hContainer, styles.itemTopContainer]}>
              <View style={{display:'flex',flexDirection:'column',alignItems:'center'}}>
                <View style={{display:'flex',flexDirection:'row',alignItems:'center'}}>
                  <Image source={{ uri: rowData.bank_logo }} style={{ width: 22, height: 22 }} />
                  <Text style={styles.name}>{rowData.name}</Text>
                </View>
                <View style={{marginTop:6}}><Text style={{fontSize:16}}>********** {rowData.card_number}</Text></View>
              </View>
              <View style={{ flex: 1 }} />
              {statusText}
            </View>
            <Divider />
            <View style={[styles.hContainer, styles.itemBottomContainer]}>
              <View style={styles.itemBottomItemContainer}>
                <Text style={styles.itemBottomLabel}>{'卡片额度'}</Text>
                <Text style={styles.itemBottomValue}>{rowData.quota}</Text>
              </View>
              <View style={styles.itemBottomItemContainer}>
                <Text style={styles.itemBottomLabel}>{'账单日'}</Text>
                <Text style={styles.itemBottomValue}>{rowData.statement_date}</Text>
              </View>
              <View style={styles.itemBottomItemContainer}>
                <Text style={styles.itemBottomLabel}>{'还款日'}</Text>
                <Text style={styles.itemBottomValue}>{rowData.repayment_date}</Text>
              </View>
            </View>
          </View>
        </CardView>
      </TouchableOpacity>
    )
  }

  render() {
    let dataList = this.props.cardManager.cardList[this.props.status] || []
    if (!this.props.status && !dataList.length) {
      dataList = dataList.concat([{
        type: 'addCard'
      }])
    }
    // let isEmpty = !dataList || !dataList.length
    // if (this.state.isLoading) {
    //   return showLoading()
    // }
    // if (isEmpty) {
    //   return <EmptyView />
    // }
    return (
      <View style={styles.container}>
        <RefreshLoadListView
          ref={this.refListView}
          dataCount={dataList.length}
          hideSeperator
          dataSource={ds.cloneWithRows(dataList)}
          renderRow={this.renderRow}
          refreshData={this.handleRefreshDatas}
          // loadMoreData={this.handleLoadMoreDatas}
          footerStyle={styles.footerStyle}
          footerTextStyle={{ color: 'transparent' }}
          autoLoadMore={false}
        />
      </View>
    )
  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5'
  },
  hContainer: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  cardStyle: {
    marginLeft: 16,
    marginRight: 16,
    backgroundColor: 'white',
    width: pageWidth - 32,
    height: (pageWidth - 32) / 343 * 155
  },
  itemContainer: {
    flex: 1,
    backgroundColor: 'white',
    borderRadius: 8
  },
  itemTopContainer: {
    minHeight: 70,
    paddingTop: 10,
    paddingBottom: 10,
    paddingLeft: 15,
    paddingRight: 18
  },
  icon: {
    width: 28,
    height: 28,
    borderRadius: 14,
    marginRight: 12,
    backgroundColor: '#f5f5f5'
  },
  name: {
    marginLeft: 12,
    fontSize: 16,
    fontWeight: 'bold',
    color: '#2e2e2e'
  },
  status: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#8e8e93'
  },
  statusFailed: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#f00'
  },
  statusCancel: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#f00'
  },
  statusMaked: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#76D358'
  },
  statusJinxinzhong: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#76D358'
  },
  statusComplate: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#378EFB'
  },
  itemBottomContainer: {
    flex: 1,
    justifyContent: 'space-around'
  },
  itemBottomItemContainer: {
    height: '100%',
    paddingTop: 25,
    paddingBottom: 25,
    alignItems: 'center',
    justifyContent: 'space-between'
  },
  itemBottomLabel: {
    fontSize: 12,
    color: '#8e8e93'
  },
  itemBottomValue: {
    fontSize: 14,
    color: '#2e2e2e'
  },
  addCardContent: {
    paddingTop: 15,
    paddingLeft: 19,
    paddingBottom: 26
  },
  footerStyle: {
  }
})